import  numpy  as  np
import matplotlib.pyplot as plt
def tmp_to_new(new_tmp:list,new:list):
    for v in new_tmp:
        new.append(v)
    return new


def pretreatment(list):
    sign = -1

    tmp     = {}
    need    = []
    new     = []
    new_tmp = []

    for sample in list:
        if sign == -1 :
            tmp['max']={
                'no':sample['no'],
                'red':sample['red'],
            }
            sign = 0
            new_tmp.append(sample['red'])
            continue
        elif sign == 0:
            new_tmp.append(sample['red'])
            if tmp['max']['red'] < sample['red']:
                #找到新的最大值
                tmp['max']={
                    'no':sample['no'],
                    'red':sample['red'],
                }

            else:
                #找到了第一个最大值

                #将上升区间写入新链
                new = tmp_to_new(new_tmp,new)
                new_tmp = []

                tmp['min']={
                    'no':sample['no'],
                    'red':sample['red'],
                }
                sign= 1
                continue
        elif sign == 1:
            if tmp['min']['red'] > sample['red']:
                tmp['min']={
                    'no':sample['no'],
                    'red':sample['red'],
                }
                new_tmp.append(sample['red'])
            else:
                #找到了一个最小  进行幅度判断
                new_tmp.append(sample['red'])
                if abs(tmp['min']['no']-tmp['max']['no']) >=4:
                    #通过 则将下降空间写入新链 并将最大写入need

                    need.append(tmp['max'])

                    new = tmp_to_new(new_tmp,new)
                    new_tmp = []

                    tmp['max']={
                        'no':sample['no'],
                        'red':sample['red'],
                    }

                    sign = 0
                else:
                    #未通过 抛弃这一段下降趋势   寻找下一个大于最大值的点 作为一个完整的上升空间
                    new_tmp = []
                    sign = 2

                #新的值作为最大的起点
                tmp.pop('min')
        elif sign == 2:
            if tmp['max']['red'] < sample['red']:
                sign = 0

                tmp['max']={
                    'no':sample['no'],
                    'red':sample['red'],
                }
                new_tmp.append(sample['red'])
            else:
                continue

    dt = 1
    t = np.arange(0, len(new), dt)
    nse = new
    r = np.exp(0 / 100)

    cnse = np.convolve(nse, r) * dt
    cnse = cnse[:len(t)]
    s = 0.1 * np.sin(2 * np.pi * t) + cnse

    plt.plot(t, s)
    plt.show()

    return need
